<template>
  <ul class="toc-list space-y-1">
    <li v-for="node in nodes" :key="node.id" class="toc-item">
      <div 
        class="toc-item-container relative pl-4"
        :style="{ 'padding-left': getPadding(node) }"
      >
        <span class="toc-indicator"></span>
        <a 
          :href="'#' + node.id" 
          class="toc-link block py-2 px-3 rounded-md font-medium transition-all duration-200"
          :class="activeId === node.id ? 'bg-indigo-50 text-indigo-700' : 'text-gray-600 hover:bg-indigo-50 hover:text-indigo-600'"
          @click.prevent="scrollToAnchor(node.id)"
        >
          {{ node.text }}
        </a>
      </div>
      
      <!-- 递归部分 -->
      <Toc 
        v-if="node.children && node.children.length" 
        :nodes="node.children" 
        :active-id="activeId"
        :base-depth="baseDepth"
        @item-clicked="handleItemClicked"
      />
    </li>
  </ul>
</template>

<script setup>
import { defineProps, defineEmits } from 'vue';

const props = defineProps({
  nodes: {
    type: Array,
    required: true,
    default: () => []
  },
  activeId: {
    type: String,
    default: ''
  },
  baseDepth: {
    type: Number,
    default: 2
  }
});

const emit = defineEmits(['item-clicked']);

// 计算每个节点的缩进值
const getPadding = (node) => {
  return `${(node.depth - props.baseDepth) * 0.75}rem`;
};

// 处理子组件的点击事件
const handleItemClicked = (id) => {
  emit('item-clicked', id);
};

// 滚动到锚点位置
const scrollToAnchor = (id) => {
  emit('item-clicked', id);
  
  const target = document.getElementById(id);
  if (target) {
    // 计算需要滚动的位置（考虑顶部导航栏高度）
    const headerHeight = document.querySelector('header')?.offsetHeight || 0;
    const topPosition = target.getBoundingClientRect().top + window.pageYOffset - headerHeight - 16;
    
    // 平滑滚动
    window.scrollTo({
      top: topPosition,
      behavior: 'smooth'
    });
  }
};
</script>

<style scoped>
.toc-list {
  list-style-type: none;
  padding-left: 0;
}

.toc-item {
  position: relative;
}

.toc-item::before {
  content: "";
  position: absolute;
  left: -0.5rem;
  top: 0;
  bottom: 0;
  border-left: 1px dashed #cbd5e1;
}

.toc-indicator {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  height: 8px;
  width: 8px;
  border-radius: 50%;
  background-color: #cbd5e1;
  z-index: 2;
}

.toc-link {
  transition: all 0.2s ease;
  position: relative;
  z-index: 1;
}

.toc-link:hover {
  transform: translateX(3px);
}
</style>